#include "superblock.h"
#include "global.h"
#include "inode.h"
#include "directoryentry.h"
#include "v6fscommands.h"

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

int cd(char *fname)                  /*inodeblocks=total # of blocks dedicated to store inode #'s*/
{
int rvalue, i;
unsigned short position, position1, fileposition;
char buffer[14];
char filename[14];
strcpy(filename, fname);

/*To open the FS file*/
if((fsfd=open("ffs", O_RDWR))<0)
	{
		printf("ERROR in mkdir: fsfd<0\n");
		exit(1);
	}

/*You have stored the current inode value i.e., cinode. Move to that inode location in the FS.*/
rvalue=lseek(fsfd, ((BLOCK_SIZE*2)+(32*cinode)+7), SEEK_SET);

/*Read the address of the data block.*/
read(fsfd, &position, sizeof(unsigned short));

/*Goto the block pointed by 'position'*/
rvalue=lseek(fsfd, position, SEEK_SET);

/*Skip the current block by 16 bytes as the first entry is always a '.'*/
position=position+16;
rvalue=lseek(fsfd, position, SEEK_SET);

/*Now, scan the block for the filename you want to do a 'cd'.*/
for(i=0;i<31;i++)
{
	fileposition=position+2;
	rvalue=lseek(fsfd, fileposition, SEEK_SET);
	read(fsfd, buffer, 14);

	if(!strcmp(buffer, filename))
		{
			fileposition=fileposition-2;
			rvalue=lseek(fsfd, fileposition, SEEK_SET);
			read(fsfd, &cinode, 2);
			/*Now move to the cinode and get the address block*/
			rvalue=lseek(fsfd, ((BLOCK_SIZE*2)+(32*cinode)+7), SEEK_SET);
			read(fsfd, &position1, SEEK_SET);
			rvalue=lseek(fsfd, position1, SEEK_SET);
			/*Now, update your current working directory.*/
			strcat(currentpath, filename);
			strcat(currentpath, "/");
			break;
		}
	else position=position+16;

	if (i==30)
		{
			printf("%s is not present in the current directory.\n");
		}
}

close(fsfd);

return 1;
}

